import {
  Component,
  OnInit,
  AfterViewInit,
  OnDestroy,
  Input,
  Renderer2,
  ViewChild,
  ViewChildren,
  QueryList,
  ElementRef
} from '@angular/core';

export interface ImageSlider {
  id: number;
  imgUrl: string;
  link: string;
  caption: string;
}

@Component({
  selector: 'app-image-slider',
  templateUrl: './image-slider.component.html',
  styleUrls: ['./image-slider.component.css']
})
export class ImageSliderComponent implements OnInit, AfterViewInit, OnDestroy {
  @Input() sliders: ImageSlider[] = [];
  @Input() sliderHeight = '160px';
  @Input() intervalBySeconds = 3;
  @ViewChild('imageSlider', { static: true }) imgSlider: ElementRef;
  @ViewChildren('img') imgs: QueryList<ElementRef>;
  timer = null;
  selectedIndex = 0;
  constructor(private rd2: Renderer2) { }

  ngOnInit() {
    console.log('imgSlider:', this.imgSlider);
    // this.imgSlider.nativeElement.innerHTML = 'HELLO';
  }
  ngAfterViewInit(): void {
    if (this.intervalBySeconds <= 0) {
      return;
    }
    console.log('AfterViewInit-imgs:', this.imgs);
    this.imgs.forEach(item => {
      console.log('AfterViewInit-img:', item.nativeElement);
      this.rd2.setStyle(item.nativeElement, 'background', '#fff');
    });
    this.timer = setInterval(() => {
      this.rd2.setProperty(this.imgSlider.nativeElement,
        'scrollLeft',
        (this.getSliderIndex(++this.selectedIndex) *
          this.imgSlider.nativeElement.scrollWidth) / this.sliders.length);
    }, this.intervalBySeconds * 1000);
  }
  getSliderIndex(idx: number): number {
    return idx >= 0 ? idx % this.sliders.length : this.sliders.length - Math.abs(idx) % this.sliders.length;
  }
  handleScroll(ev) {
    const ratio = ev.target.scrollLeft / (ev.target.scrollWidth / this.sliders.length);
    this.selectedIndex = Math.round(ratio);
  }
  ngOnDestroy(): void {
    clearInterval(this.timer);
  }
}
